import { ElMessage } from 'element-plus';
import { defineStore } from 'pinia';
import {
  reqCategory1,
  reqCategory2,
  reqCategory3,
  type categoryItemType,
} from "@/api/category"

// state类型
interface StateType {
  category1List: categoryItemType[],
  category1Id: number | null,
  category2List:categoryItemType[],
  category2Id: number | null,
  category3List:categoryItemType[],
  category3Id: number | null,
}

export const useCategoryStore = defineStore('category', {
  state: ():StateType => {
    return {
      // 一级分类数据
      category1List: [],
      category1Id: null,
      // 二级分类数据
      category2List:[],
      category2Id:null,
      // 三级分类数据
      category3List:[],
      category3Id:null,
    }
  },
  actions:{
    // 获取一级分类请求函数
    async getCategory1List() {
      try {
        const res = await reqCategory1()
        this.category1List = res
      } catch (e) {
        return Promise.reject(e)
      }
    },
    // 获取二级列表分类请求函数
    async getCategory2List(category1Id:number) {
      try {
        const res = await reqCategory2(category1Id)
        this.category2List = res
      } catch (e) {
        ElMessage.error('获取二级列表失败')
      }
    },

    // 获取三级列表分类请求
    async getCategory3List(category2Id:number) {
      try {
        const res = await reqCategory3(category2Id)
        this.category3List = res
      } catch (e) {
        ElMessage.error('获取三级列表失败')
      }
    },

  }
})